package com.jrx.anytxn.param.service.system.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jrx.anytxn.i18n.response.TxnPage;
import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.common.uitl.BeanMapping;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.constant.ErrorMsgConstant;
import com.jrx.anytxn.param.dto.system.OrganizationTableReq;
import com.jrx.anytxn.param.dto.system.OrganizationTableRes;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.ext.ExtPrOrganizationTableMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 机构表 业务接口实现
 *
 * @author yx
 * @date 2019/5/28
 */
@Service
@CacheConfig(cacheNames = "ORGANIZATION")
public class OrganizationTableServiceImpl implements IOrganizationTableService {
    private static final Logger logger = LoggerFactory.getLogger(OrganizationTableServiceImpl.class);
    @Resource
    private ExtPrOrganizationTableMapper extPrOrganizationTableMapper;

    @Autowired
    private ISegmentService segmentService;


    @Override
    public TxnPage<OrganizationTableRes> findAllPageByTenId(Integer pageNum, Integer pageSize, String tenantId) throws TxnException {
        Page<PrOrganizationTable> page = PageHelper.startPage(pageNum, pageSize,Constant.ORDER_BY_SORT);
        List<PrOrganizationTable> organizationTableList = extPrOrganizationTableMapper.selectAllByTenId(tenantId);
        if (organizationTableList.isEmpty()) {
            logger.error(TxnRespCode.NO_DATA.getMsg());
            throw new TxnException(TxnRespCode.NO_DATA.getMsg());
        }
        List<OrganizationTableRes> res = BeanMapping.copyList(organizationTableList, OrganizationTableRes.class);
        return new TxnPage<>(pageNum, pageSize, page.getTotal(), res);
    }

    @Override
    public List<OrganizationTableRes> findAllOrgByTenId(String tenantId) {
        List<PrOrganizationTable> prOrganizationTables = extPrOrganizationTableMapper.selectAllByTenId(tenantId);
        return BeanMapping.copyList(prOrganizationTables, OrganizationTableRes.class);

    }

    @Override
    public OrganizationTableRes addOrganizationTable(OrganizationTableReq organizationTableReq) throws TxnException {
        PrOrganizationTable organizationTable = extPrOrganizationTableMapper.selectByOrganizationId(organizationTableReq.getOrganizationId(), organizationTableReq.getTenantId());
        if (organizationTable != null) {
            logger.error(TxnRespCode.DATA_EXISTS.getMsg());
            throw new TxnException(TxnRespCode.DATA_EXISTS.getMsg());
        }
        PrOrganizationTable prOrganizationTable = BeanMapping.copy(organizationTableReq, PrOrganizationTable.class);
        try {
            prOrganizationTable.setId(segmentService.getId(Constant.PR_ORGANIZATION_TABLE));
        } catch (SegmentException e) {
            logger.error("主键生成错误",e);
            throw new TxnException(ErrorMsgConstant.ERROR_ID);
        }

        prOrganizationTable.setRecordVersionNumber(Constant.VERSION_NUMBER);
        //添加时批次状态默认为正常
        prOrganizationTable.setBatchInProgressFlag(Constant.ORG_BATCH_FLAG_0);
        prOrganizationTable.setToday(new Date());
        extPrOrganizationTableMapper.insertSelective(prOrganizationTable);
        return BeanMapping.copy(prOrganizationTable, OrganizationTableRes.class);
    }

    @Caching(evict={@CacheEvict(key="'org_'+#organizationTableReq.organizationId"), @CacheEvict( key="'org_" +
            "'+#organizationTableReq.tenantId+'_'+#organizationTableReq.organizationId")})
    @Override
    public OrganizationTableRes modifyOrganizationTable(OrganizationTableReq organizationTableReq) throws TxnException {

        PrOrganizationTable prOrganizationTable = extPrOrganizationTableMapper.selectByIdAndTenId(organizationTableReq.getId(),organizationTableReq.getTenantId());
        if (prOrganizationTable == null) {
            logger.error(TxnRespCode.NO_DATA.getMsg());
            throw new TxnException(TxnRespCode.NO_DATA.getMsg());
        }

        PrOrganizationTable organizationTable = BeanMapping.copy(organizationTableReq, PrOrganizationTable.class);
        // 更新
        extPrOrganizationTableMapper.updateByPrimaryKeySelectiveAndNotNull(organizationTable);
        return BeanMapping.copy(organizationTable, OrganizationTableRes.class);

    }


    @Caching(evict={@CacheEvict(key="'org_'+#organizationId"), @CacheEvict( key="'org_'+#tenantId+'_'+#organizationId")})
    @Override
    public Boolean removeByIdAndTenId(String organizationId, String tenantId) throws TxnException {
        if (organizationId == null || tenantId == null) {
            logger.error(TxnRespCode.NOT_EMPTY.getMsg());
            throw new TxnException(TxnRespCode.NOT_EMPTY.getMsg());
        }
        int i = extPrOrganizationTableMapper.deleteByIdAndTenId(organizationId, tenantId);
        return i > 0;
    }

    @Override
    public OrganizationTableRes findByIdAndTenId(Long id, String tenantId) throws TxnException {
        if (id == null || tenantId == null) {
            logger.error(TxnRespCode.NOT_EMPTY.getMsg());
            throw new TxnException(TxnRespCode.NOT_EMPTY.getMsg());
        }
        PrOrganizationTable organizationTable = extPrOrganizationTableMapper.selectByIdAndTenId(id, tenantId);
        return BeanMapping.copy(organizationTable, OrganizationTableRes.class);
    }

    @Cacheable(key="'org_'+#tenantId+'_'+#orgId")
    @Override
    public PrOrganizationTable findByOrId(String orgId, String tenantId) throws TxnBizException {
        PrOrganizationTable organizationTable = extPrOrganizationTableMapper.selectByOrganizationId(orgId, tenantId);
        if (organizationTable == null) {
            throw new TxnBizException(TxnRespCode.NO_DATA.getCode(), TxnRespCode.NO_DATA.getMsg(ErrorMsgConstant.ORG));
        }
        return organizationTable;
    }

    @Cacheable(key="'org_'+#organizationId")
    @Override
    public PrOrganizationTable findByOrgIdForBatch(String organizationId){
        return extPrOrganizationTableMapper.selectByOrgIdForBatch(organizationId);
    }


}
